<template>
  <div class="container MaterialMange" style="width:99%;margin-top:-25px;">
    <!-- 查询条件 -->
    <div class="query-box">
      <el-form :model="queryBox" status-icon ref="queryBox">
        <el-row>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">素材类别</div>
              <el-select clearable filterable v-model="queryBox.materielType" filterable>
                <el-option
                  v-for="item in materiel_type_option"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="depart-box">
              <el-form-item label prop="customerNumber">
                <el-input v-model="queryBox.code" placeholder="素材编码">
                  <template slot="prepend">素材编码</template>
                </el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="depart-box">
              <el-form-item label prop="customerNumber">
                <el-input v-model="queryBox.name" placeholder="素材名称">
                  <template slot="prepend">素材名称</template>
                </el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">分类</div>
              <el-form-item>
                <el-select clearable filterable v-model="queryBox.platformType" placeholder="请选择">
                  <el-option
                    v-for="item in bc_material_platform_type_options"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  >{{item.value}}</el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="4">
              <div class="depart-box">
              <el-form-item label prop="uploadUser">
                <el-input v-model="queryBox.uploadUser" placeholder="上传人">
                  <template slot="prepend">上传人</template>
                </el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">状态</div>
              <el-form-item>
                <el-select clearable filterable v-model="queryBox.useState" placeholder="请选择">
                  <el-option
                    v-for="item in bc_materiel_use_state_options"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  >{{item.value}}</el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="9">
            <div class="depart-box" style="margin-bottom:20px;">
              <div class="slect-title" style="width:150px;">使用期限</div>
              <el-date-picker
                v-model="useDateTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
          </el-col>
          <el-col :span="9">
            <div class="depart-box" style="margin-bottom:20px;">
              <div class="slect-title" style="width:150px;">更新时间</div>
              <el-date-picker
                v-model="upDateTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">停启</div>
              <el-form-item>
                <el-select clearable filterable v-model="queryBox.onlineState" placeholder="请选择">
                  <el-option
                    v-for="item in isopen"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div class="from-btns">
        <kt-button
          :label="$t('action.reset')"
          perms="true"
          type="primary"
          @click="reset('queryBox')"
        />
        <kt-button
          :label="$t('action.search')"
          perms="true"
          type="primary"
          @click="search"
        />
      </div>
    </div>
    <!-- 批量删除按钮 -->
    <div class="add-btns fl">
      <kt-button
        :label="$t('新增文章素材')"
        perms="MarketingManage:MaterialMange:newAdd"
        type="primary" 
        @click="newAdd"
      />
    </div>
    <!--表格内容栏-->
    <div class="btn">
      <Crm-table
        class="table-width"
        MaterialMange
        width="400"
        :showBatchDelete="false"
        permsSee="MarketingManage:MaterialMange:see"
        permsEdit="MarketingManage:MaterialMange:edit"
        permsDelete="MarketingManage:MaterialMange:delete"
        permsAdd="MarketingManage:MaterialMange:top"
        :data="pageResult"
        :columns="columns"
        :loading='loading'
        @findPage="findPage"
        @changeSwitch="changeSwitch"
        @handleEdit="handleEdit"
        @handleSee="handleSee"
        @handleOrder='toTOP'
        @handleDeleteDic='handleDelete'
        @handleRemoveTop='handleRemoveTop'
      ></Crm-table>
    </div>
    <el-dialog
      class="add-pop add-MaterialMangePop"
      :title="operation ? '新增文章素材' : '编辑文章素材'"
      width="40%"
      @close="closePop"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false">
        <el-form
          label-width="110px"
          :model="dataFormAdd"
          :rules="buryingConfigRule"
          ref="dataFormAdd"
        >
        <el-form-item label="素材类别" prop="materielType">
            <el-select clearablefilterable v-model="dataFormAdd.materielType" filterable>
                <el-option
                  v-for="item in materiel_type_option"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="分类" prop="platformType">
            <el-select clearable filterable @change="materielTypeChange"  v-model="dataFormAdd.platformType"   filterable>
                <el-option
                  v-for="item in bc_material_platform_type_options"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="素材编码" prop="code">
              <el-input
              :disabled="true"
              v-model="dataFormAdd.code"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="素材名称" prop="name">
              <el-input
              v-model="dataFormAdd.name"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="使用期限" prop="useDate">
            <el-date-picker
                v-model="dataFormAdd.useDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :size="size" @click.native="closePop">{{$t('action.cancel')}}</el-button>
          <el-button
            :size="size"
            type="primary"
            v-if='operation'
            @click.native="addBuryingConfig('dataFormAdd')"
            :loading="editLoading"
          >提交</el-button>
          <el-button
            :size="size"
            v-if='!operation'
            type="primary"
            @click.native="eidtBuryingConfig('dataFormAdd')"
            :loading="editLoading"
          >提交</el-button>
        </div>
      </el-dialog>
  </div>
</template>
<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import CrmSwitch from "@/views/Core/CrmSwitch";
import { regionDataPlus } from "element-china-area-data";
import { CodeToText } from "element-china-area-data";
import WebUpload from "@/components/common/upload/WebUpload";
import { baseUrl } from "@/utils/global";
import axios from "axios";
import Cookies from "js-cookie"
export default {
  name: "MaterialMange",
  components: {
    PopupTreeInput,
    CrmTable,
    KtButton,
    CrmSwitch
  },
  data() {
    return {
      size:'small',
      // 查询条件
      isopen: [
        {
          value: "启用",
          key: "1"
        },
        {
          value: "停用",
          key: "2"
        }
      ],
      useDateTime:[],
      upDateTime:[],
      queryBox: {
        materialPlatformType:'',
        materielType:'',
        materielState:'',
        state:'',
        onlineState:'',
        code:'',
        name:'',
        platformType:'',
        uploadUser:'',
        useState:''
      },
      dataFormAdd:{
        useDate:'',
        materielType:'',
        platformType:'',
        code:'',
        useDate:'',
        name:''
      },
      width: 200,
      columns: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "materielTypeStr", label: "素材类别", minWidth: 100 },
        { prop: "code", label: "素材编码", minWidth: 150 },
        { prop: "name", label: "素材名称", minWidth: 150 },
        { prop: "platformTypeStr", label: "分类", minWidth: 100 },
        { prop: "useTimeStr", label: "使用期限", minWidth: 220 },
        { prop: "updateTime", label: "更新时间", minWidth: 150 },
        { prop: "uploadUser", label: "上传人", minWidth: 100 },
        { prop: "useStateStr", label: "状态", minWidth: 100 }
      ],
      buryingConfigRule: {
        materielType: [
          { required: true, message: '请填写物料类别', trigger: 'blur' }
        ],
        platformType: [
          { required: true, message: '请填写分类', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请填写物料名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请填写物料编码', trigger: 'blur' }
        ],
        // useDate :[
        //   { required: true, message: '请选择使用期限', trigger: 'change' }
        // ],
      },
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {
        content: []
      },
      useDate:[],
      operation: false, // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      materiel_type_option:[],
      bc_material_platform_type_options:[],
      bc_materiel_use_state_options:[],
      loading: false, // 加载标识
      editLoading:false,
      userList:[]
    };
  },
  methods: {
    // 搜索
    search() {
      this.loading=true
      this.pageRequest.pageNum = 1;
      if(this.upDateTime){
        this.queryBox.updateTimeStart=this.upDateTime[0]
        this.queryBox.updateTimeEnd=this.upDateTime[1]
      }
      if(this.useDateTime){
        this.queryBox.useStartTime=this.useDateTime[0]
        this.queryBox.useEndTime=this.useDateTime[1]
      }
      this.findPage(null)
    },
    get_downList(){
      // 素材类别
      this.materiel_type_option = JSON.parse(
        localStorage.getItem("bcMaterialType")
      );
      // 分类
      this.bc_material_platform_type_options = JSON.parse(
        localStorage.getItem("bcMaterialPlatformType")
      );
      // 状态
      this.bc_materiel_use_state_options = JSON.parse(
        localStorage.getItem("bcMaterielUseStateOptions")
      );
      this.$api.person.findPage({userType:3}).then(res=>{
        if(res.result==1){
          this.userList=res.userInfoList
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    handleChange(value) {
    },
    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.loading=true
        this.pageRequest = data.pageRequest;
      }
      this.queryBox.pageSize = this.pageRequest.pageSize;
      this.queryBox.pageNum = this.pageRequest.pageNum;
      this.queryBox.manageType = '3'
      this.$api.agent.materielFileManageList(this.queryBox).then(res=>{
        if(res.result==1){
          this.loading=false
          let content = { content: res.data, totalSize: res.total };
          this.pageResult = content;
          this.pageResult.content.forEach(item=>{
            this.materiel_type_option.forEach(mtItem=>{
              if(mtItem.key==item.materielType){
                item.materielTypeStr=mtItem.value
              }
            })
            item.useStartTimeStr=/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.useStartTime)
            item.useEndTimeStr=/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.useEndTime)
            item.useTimeStr=item.useStartTimeStr+'--'+item.useEndTimeStr
            this.bc_material_platform_type_options.forEach(pItem=>{
              if(pItem.key==item.platformType){
                item.platformTypeStr=pItem.value
              }
            })
            this.bc_materiel_use_state_options.forEach(bcusItem=>{
              if(bcusItem.key==item.useState){
                item.useStateStr=bcusItem.value
              }
            })
          })
        }
      })
    },
    // 添加
    addBuryingConfig(dataFormAdd){
      this.dataFormAdd.manageType=3 //1:物料管理  2：推广活动管理 3:文章素材管理
      this.$refs[dataFormAdd].validate(valid=>{
        if(valid){
          if(this.dataFormAdd.useDate){
              this.dataFormAdd.useStartTime=this.dataFormAdd.useDate[0],
              this.dataFormAdd.useEndTime=this.dataFormAdd.useDate[1]
          }
          if(this.dataFormAdd.useDate.length==0){
             this.dataFormAdd.useStartTime='2001-12-31 23:59:59',
              this.dataFormAdd.useEndTime='2099-12-31 23:59:59'
          }
          this.$api.agent.materielFileManageInsert(this.dataFormAdd).then(res=>{
            if(res.result==1){
              this.$message.success(res.msg);
              this.closePop()
              this.findPage(null)
            }else{
              this.$message.error(res.msg)
            }
          })
          
        }
      })
    },
    handleEdit(params){
      this.dialogVisible=true
      this.operation=false
      
      this.dataFormAdd=params.row
      let newArry=[]
      newArry.push(params.row.useStartTime,params.row.useEndTime)
      this.dataFormAdd.useDate=newArry
    },
    eidtBuryingConfig(dataFormAdd){
      this.editLoading=true
      this.$refs[dataFormAdd].validate(valid=>{
        if(valid){
          if(this.useDate){
              this.dataFormAdd.useStartTime=this.dataFormAdd.useDate[0],
              this.dataFormAdd.useEndTime=this.dataFormAdd.useDate[1]
            }
          this.$api.agent.materielFileManageUpdate(this.dataFormAdd).then(res=>{
            if(res.result==1){
              this.editLoading=false
              this.$message.success(res.msg);
              this.closePop()
              this.findPage(null)
            }else{
              this.$message.error(res.msg)
            }
          })
          
        }
      })
    },
    materielTypeChange(val){
      this.$api.agent.materielFileManagecodeCreate({ type:val}).then(res=>{
        if(res.errorCode==0){
          this.dataFormAdd.code=res.msg
        }
      })
    },
    // 重置
    reset(queryBox) {
      this.$refs.queryBox.resetFields();
      this.queryBox.materielType=''
      this.queryBox.code=''
      this.queryBox.name=''
      this.queryBox.platformType=''
      this.queryBox.uploadUser=''
      this.queryBox.useState=''
      this.useDateTime=''
      this.queryBox.useStartTime=''
      this.queryBox.useEndTime=''
      this.upDateTime=''
      this.queryBox.useEndTime=''
      this.queryBox.updateTimeStart=''
      this.queryBox.upateTimeEnd=''
      this.queryBox.onlineState=''
      this.queryBox.updateTimeEnd=''
      this.findPage(null);
    },
    newAdd() {
      this.dialogVisible=true
      this.operation=true
    },
    closePop(){
      this.dialogVisible=false
      this.operation=false
      this.dataFormAdd.code=''
      this.dataFormAdd.platformType=''
      this.dataFormAdd.materielType=''
      this.dataFormAdd.name=''
      this.dataFormAdd.useDate=''
      this.dataFormAdd.useStartTime=''
      this.dataFormAdd.useEndTime=''
    },
    handleDelete(params){
      this.$confirm('确定删除此项？','提示',{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(()=>{
        this.$api.agent.materielFileManageDelete({id:params.row.id}).then(res=>{
          if(res.result==1){
            this.$message.success(res.msg)
            this.findPage(null)
          }else{
            this.$message.error(res.msg)
          }
        })
      })
      
    },
    // 锁定
    changeSwitch(value){
      this.dataFormAdd.onlineState=value.row.onlineState
      this.$api.agent.materielFileManageUpdate({id:value.row.id,onlineState:this.dataFormAdd.onlineState}).then(res=>{
        if(res.result==1){
          this.$message.success(res.msg);
          this.closePop()
          this.findPage(null)
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    // 文件管理
    handleSee(params){
      this.$router.push({
        path: "/MarketingManage/MaterialPackage",
        query: {
          id: params.row.id,
          materielName:params.row.name,//物料包名称
          materielType:params.row.materielType,//物料类型
          code:params.row.code,//物料编码
          platformType:params.row.platformType,//平台类型（分类）
          manageType:3 //1:物料管理  2：推广活动管理 3:文章素材管理  物料包类型
        }
      });
    },
    toTOP(params){
      this.$api.agent.materielFileManageToTop({id:params.row.id}).then(res=>{
        if(res.result==1){
          this.$message.success(res.msg);
          this.closePop()
          this.findPage(null)
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    // 取消置顶
    handleRemoveTop(params){
      this.$api.agent.materielFileManageRemoveToTop({id:params.row.id}).then(res=>{
        if(res.result==1){
          this.$message.success(res.msg);
          this.closePop()
          this.findPage(null)
        }else{
          this.$message.error(res.msg)
        }
      })
    }
  },
  mounted() {
    this.get_downList()
  }
};
</script>
<style >
@import url("../../assets/queryBox.css");
</style>
<style lang='scss' scoped>
.MaterialMange{
  .depart-box{
    .el-form-item{
      width: 100%;
    }
    
  }
  
}
.checked-person {
  font-weight: 500;
  display: inline-block;
  text-align: center;
  margin: 3% 0 3% 0;
}
.batchdistribution-pop-tit{
  font-size: 20px;
  font-weight: bold;
  display: inline-block;
  color: #303133;
}
.demo-form-inline{
  width: 90%;
  margin: 0 auto;
  .el-dialog__body .el-input{
    width: 93% !important;
  }
  .el-select{
    width: 100% !important;
  }
  .tit{
    display: inline-block;
    margin-top: 10%;
  }
}
.el-row .el-col{
  margin-left: 0;
}
.query-box .el-row .el-col{
  margin-left: 2%;
}
.el-dialog__wrapper .el-form-item__content{
  margin-left: 0;
}
</style>
<style lang='scss'>
.batchdistribution-pop .el-dialog__header{
  padding: 0 0 0 0 !important;
}
.add-MaterialMangePop{
  .el-range-editor.el-input__inner{
    width: 100%;
  }
}
.MaterialMange{
  .btn{
    .el-button+.el-button{
      width: 20px 
    }
  }
}
</style>



